package org.example.coursemangementserver.server.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.coursemangementserver.common.result.Result;
import org.example.coursemangementserver.common.utils.AliOssUtil;
import org.example.coursemangementserver.pojo.vo.UpFileVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author 12438
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    /**
     * 阿里云存储工具
     */
    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 处理文件上传
     * @param file
     * @return
     */
    @PostMapping("/uploadFile")
    public Result<UpFileVO> uploadFile(MultipartFile file) {
        log.info("正在处理前端上传文件请求： " + file.getOriginalFilename());
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID()+ originalFilename.substring(originalFilename.lastIndexOf("."));
        try {
            String url = aliOssUtil.upload(file.getBytes(), fileName);
            UpFileVO upFileVO = new UpFileVO(url);
            return Result.success(upFileVO);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.error("上传失败");
    }
}
